package com.dzt.cloudreader.fragment;

import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.LinearLayoutManager;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import com.dzt.cloudreader.R;
import com.dzt.cloudreader.adapter.EverydayAdapter;
import com.dzt.cloudreader.base.LoadingFragment;
import com.dzt.cloudreader.interfaces.PerfectClickListener;
import com.dzt.cloudreader.model.FrontpageBean.ResultBeanXXXXXXXXXXXXXXX.FocusBean;
import com.dzt.cloudreader.model.GankIoDayBean.ResultsBean.AndroidBean;
import com.dzt.cloudreader.network.GankIoDayPresenter;
import com.dzt.cloudreader.network.GankIoDayView;
import com.dzt.cloudreader.network.GlideImageLoader;
import com.dzt.cloudreader.network.TingPresenter;
import com.dzt.cloudreader.network.TingView;
import com.dzt.cloudreader.rxbus.RxBus;
import com.dzt.cloudreader.rxbus.RxBusBaseMessage;
import com.dzt.cloudreader.rxbus.RxCodeConstants;
import com.dzt.cloudreader.utils.JLogKit;
import com.dzt.cloudreader.utils.JTimeKit;
import com.dzt.cloudreader.webview.WebViewActivity;
import com.dzt.xrecyclerview.XRecyclerView;
import com.youth.banner.Banner;
import com.youth.banner.listener.OnBannerClickListener;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import butterknife.BindView;

/**
 * Created by M02323 on 2017/12/15.
 * 每日推荐
 * 更新逻辑：判断是否是第二天(相对于2017-12-16)
 * 是：判断是否是大于12：30
 * *****     |是：刷新当天数据
 * *****     |否：使用缓存：|无：请求前一天数据,直到请求到数据为止
 * **********             |有：使用缓存
 * 否：使用缓存 ： |无：请求今天数据
 * **********    |有：使用缓存
 */

public class EverydayFragment extends LoadingFragment {

    @BindView(R.id.xrv_everyday)
    XRecyclerView recyclerView;
    Banner banner;
    private List<List<AndroidBean>> resultList = new ArrayList<>();
    private List<String> bannerImages = new ArrayList<>();
    private View mHeaderView;
    private View mFooterView;
    private EverydayAdapter mEverydayAdapter;
    private GankIoDayPresenter presenter;
    private TingPresenter tingPresenter;
    private LayoutInflater inflater;
    private int countShow = 0;
    // 是否是上一天的请求
    private boolean isOldDayRequest;
    // 记录请求的日期
    String year = getTodayTime().get(0);
    String month = getTodayTime().get(1);
    String day = getTodayTime().get(2);

    @Override
    protected int getLayoutId() {
        return R.layout.fragment_everyday;
    }

    @Override
    protected void initData() {
        inflater = LayoutInflater.from(context);
        mEverydayAdapter = new EverydayAdapter(context, resultList, R.layout.item_everyday_title);
        initRecyclerView();
        presenter = new GankIoDayPresenter(context);
        presenter.onCreate();
        presenter.attachView(gankIoView);
        presenter.getGankIoDay(year, month, day);
        tingPresenter = new TingPresenter(context);
        tingPresenter.onCreate();
        tingPresenter.attachView(tingView);
        tingPresenter.getFrontpage();
    }

    private void initRecyclerView() {
        recyclerView.setPullRefreshEnabled(false);
        recyclerView.setLoadingMoreEnabled(false);
        if (mHeaderView == null) {
            mHeaderView = inflater.inflate(R.layout.header_item_everyday, null, false);
            banner = mHeaderView.findViewById(R.id.banner);
            recyclerView.addHeaderView(mHeaderView);
        }
        if (mFooterView == null) {
            mFooterView = inflater.inflate(R.layout.footer_item_everyday, null, false);
            recyclerView.addFootView(mFooterView, true);
            recyclerView.noMoreLoading();
        }
        recyclerView.setLayoutManager(new LinearLayoutManager(getContext()));
        // 需加，不然滑动不流畅
        recyclerView.setNestedScrollingEnabled(false);
        recyclerView.setHasFixedSize(false);
        recyclerView.setItemAnimator(new DefaultItemAnimator());
        recyclerView.setAdapter(mEverydayAdapter);
        initLocalSetting();
    }

    private void initLocalSetting() {
        TextView tvDailyText = mHeaderView.findViewById(R.id.tv_daily_text);
        ImageView ibXiandu = mHeaderView.findViewById(R.id.ib_xiandu);
        ImageView ibMovieHot = mHeaderView.findViewById(R.id.ib_movie_hot);
        // 显示日期,去掉第一位的"0"
        tvDailyText.setText(getTodayTime().get(2).indexOf("0") == 0 ?
                getTodayTime().get(2).replace("0", "") : getTodayTime().get(2));
        ibXiandu.setOnClickListener(new PerfectClickListener() {
            @Override
            protected void onNoDoubleClick(View v) {
                WebViewActivity.loadUrl(v.getContext(), "https://gank.io/xiandu", "加载中...");
            }
        });
        ibMovieHot.setOnClickListener(new PerfectClickListener() {
            @Override
            protected void onNoDoubleClick(View v) {
                RxBus.getDefault().post(RxCodeConstants.JUMP_TYPE_TO_ONE, new RxBusBaseMessage());
            }
        });
    }

    @Override
    protected void onRefresh() {
        super.onRefresh();
        countShow = 0;
        presenter.getGankIoDay(year, month, day);
        tingPresenter.getFrontpage();
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        if (presenter != null) {
            presenter.onDestroy();
        }
        if (tingPresenter != null) {
            tingPresenter.onDestroy();
        }
    }

    private GankIoDayView gankIoView = new GankIoDayView() {

        @Override
        public void onSuccess(List<List<AndroidBean>> lists) {
            countShow++;
            if (countShow >= 2) {
                showContentView();
            }
            if (lists == null || lists.size() <= 0) {
                requestBeforeData();
            } else {
                JLogKit.getInstance().i("year = " + year + " month = " + month + " day = " + day);
                resultList.clear();
                resultList.addAll(lists);
                mEverydayAdapter.notifyDataSetChanged();
            }
        }

        @Override
        public void onError(String result) {
            JLogKit.getInstance().e("onError ");
            showError();
        }
    };

    /**
     * 没请求到数据就取缓存，没缓存一直请求前一天数据
     */
    private void requestBeforeData() {
//		mLists = (ArrayList<List<AndroidBean>>) maCache.getAsObject(Constants.EVERYDAY_CONTENT);
//		if (mLists != null && mLists.size() > 0) {
//			setAdapter(mLists);
//		} else {
        // 一直请求，知道请求到数据为止
        ArrayList<String> lastTime = JTimeKit.getLastTime(year, month, day);
        presenter.getGankIoDay(lastTime.get(0), lastTime.get(1), lastTime.get(2));
        year = lastTime.get(0);
        month = lastTime.get(1);
        day = lastTime.get(2);
        //showContentData();
        //}
    }

    private TingView tingView = new TingView() {
        @Override
        public void onSuccess(final FocusBean ting) {
            countShow++;
            if (countShow >= 2) {
                showContentView();
            }
            bannerImages.clear();
            if (ting == null)
                return;
            for (FocusBean.ResultBeanXXXXXXXXXXX bean : ting.getResult()) {
                bannerImages.add(bean.getRandpic());
            }
            banner.setImages(bannerImages).setImageLoader(new GlideImageLoader()).start();
            banner.setOnBannerClickListener(new OnBannerClickListener() {
                @Override
                public void OnBannerClick(int position) {
                    position = position - 1;
                    // 链接没有做缓存，如果轮播图使用的缓存则点击图片无效
                    if (ting.getResult().get(position) != null && ting.getResult().get(position).getCode() != null
                            && ting.getResult().get(position).getCode().startsWith("http")) {
                        WebViewActivity.loadUrl(getContext(), ting.getResult().get(position).getCode(), "加载中...");
                    }
                }
            });
        }

        @Override
        public void onError(String result) {
            showError();
        }
    };

    /**
     * 获取当天日期
     */
    private ArrayList<String> getTodayTime() {
        SimpleDateFormat sDateFormat = new SimpleDateFormat("yyyy-MM-dd");
        String date = sDateFormat.format(new Date());
        String[] split = date.split("-");
        String year = split[0];
        String month = split[1];
        String day = split[2];
        ArrayList<String> list = new ArrayList<>();
        list.add(year);
        list.add(month);
        list.add(day);
        return list;
    }
}
